<!--  小区选择封装  -->
<template>
	<el-form-item v-if="state.roleIds.includes(1)" :label="props.showLabel ? '组织' : ''">
		<orgSelect :no-data="props.noData" :dept-id="userInfos.deptId" @selected="onOrgSelect" @orgSeleced="orgTopSelect" />
	</el-form-item>

	<el-form-item :label="props.showLabel ? '小区' : ''">
		<el-select
			size="default"
			v-model="state.communityName"
			clearable
			filterable
			remote
			reserve-keyword
			placeholder="小区关键词"
			:remote-method="getCommunityData"
			:loading="state.communityLoading"
			@change="communityChange"
			style="width: 150px"
			empty-text="暂无数据"
		>
			<el-option v-for="item in state.communityOptions" :key="item.id" :label="item.name" :value="item" />
		</el-select>
	</el-form-item>

	<el-form-item :label="props.showLabel ? '楼栋' : ''" v-if="state.queryParams.communityId && props.showBuild">
		<el-select
			size="default"
			style="width: 80px"
			v-model="state.queryParams.buildNum"
			clearable
			reserve-keyword
			placeholder="楼栋"
			@change="buildChange"
		>
			<el-option v-for="item in state.buildSelect" :key="item" :label="item" :value="item" />
		</el-select>
	</el-form-item>

	<el-form-item :label="props.showLabel ? '单元' : ''" v-if="state.queryParams.buildNum && props.showUtil">
		<el-select
			v-model="state.queryParams.utilNum"
			reserve-keyword
			placeholder="单元"
			:loading="state.communityLoading"
			@change="unitChange"
			style="width: 80px"
		>
			<el-option v-for="item in state.unitSelect" :key="item" :label="item" :value="item" />
		</el-select>
	</el-form-item>
</template>

<script lang="ts" setup name="device">
import { reactive, onMounted, ref, watch, computed } from 'vue';
import { storeToRefs } from 'pinia';

import orgSelect from './orgSelect.vue';
import communityApi from '/@/api/smoke/community';
import deviceApi from '/@/api/smoke/device';
import alarmManageApi from '/@/api/smoke/alarmManage';
import { Session } from '/@/utils/storage';
import { useUserInfo } from '/@/stores/userInfo';

const stores = useUserInfo();
const { userInfos, roleIds, communitys } = storeToRefs(stores);
const props = defineProps({
	noData: {
		type: Array,
		default: () => {
			return ['其他', '安装人员'];
		},
	},
	expandAll: {
		type: Boolean,
		default: true,
	},
	showLabel: {
		type: Boolean,
		default: true,
	},
	showBuild: {
		type: Boolean,
		default: true,
	},
	showUtil: {
		type: Boolean,
		default: true,
	},
});

// emit
const emit = defineEmits(['doSearch']);

// 是否是巡检员（是否可以使用组织）
const isXJY = computed(() => {
	let noUseArr = [3, 4]; // 巡检员和安装人员都不能使用组织
	let flag = true;

	//  单角色
	if (roleIds.value.length == 1) {
		roleIds.value.forEach((item: number) => {
			if (!noUseArr.includes(item)) {
				flag = false;
			}
		});
	}

	//  多角色
	if (roleIds.value.length > 1) {
		roleIds.value.forEach((item: number) => {
			if (!noUseArr.includes(item)) {
				flag = false;
			}

			if (noUseArr.includes(item) && [1, 3, 5].includes(item)) {
				flag = false;
			}
		});
	}

	return flag;
});

const communityOptions = computed(() => {
	let a = communitys.value.map((item: any) => {
		return {
			name: item.name,
			id: item.communityId,
		};
	});
	return a;
});

const state = reactive({
	communityName: '',
	buildSelect: [],
	unitSelect: [],
	communityLoading: false,
	communityOptions: communityOptions.value,
	queryParams: {
		deptIds: [],
		dept: <any>null,
		communityId: '', // 小区ID
		communityIds: <any>[],
		buildNum: '', // 小区栋数
		utilNum: '', // 小区单元
	},
	roleIds: roleIds.value??[],
});

onMounted(() => {
	state.queryParams.communityIds = communitys.value.map((item: any) => item.communityId);

	// roleIds 非超管 获取小区
	if (!roleIds.value.includes(1) && userInfos.value.deptId != 100) {
		state.queryParams.dept = userInfos.value.deptId;
		getCommunityByDeptId([userInfos.value.deptId]);
	}

	// 是巡检员，取本地小区信息
	if (isXJY.value) {
		if (!communitys.value.length) {
			getCommunityByUserId(userInfos.value.id);
		}
		// else {
		// 	emit('doSearch', state.queryParams);
		// }
		return;
	}
	// emit('doSearch', state.queryParams);
});

// 通过用户ID获取小区
function getCommunityByUserId(userId: any) {
	let params = {
		userId,
	};
	alarmManageApi.getCommunityByUserId(params).then((res) => {
		Session.set('communitys', res.data.list);
		useUserInfo().setCommunitys();

		state.communityOptions = res.data.list.map((item: any) => {
			return {
				name: item.name,
				id: item.communityId,
			};
		});
		state.queryParams.communityIds = res.data.list.map((item: any) => item.communityId);
		emit('doSearch', state.queryParams);
	});
}

// 查询小区
function getCommunityData(value?: any) {
	if (!value.trim()) return; // 查询为空，退出
	communityApi.getCommunityList({ keyWord: value }).then((res: any) => {
		let list = res.data.list.map((item: any) => {
			return {
				name: item.name,
				id: item.id,
			};
		});
		state.communityOptions = list;
	});
}

// 通过选择组织（部门）查询小区
function getCommunityByDeptId(ids: any) {
	let prarams = {
		deptIds: ids,
	};

	communityApi.getCommunityListByDeptId(prarams).then((res: any) => {
		let list = res.data.list.map((item: any) => {
			return {
				name: item.name,
				id: item.id,
			};
		});

		state.communityOptions = list;
		state.queryParams.communityId = '';
		state.communityName = '';
		state.queryParams.buildNum = '';
		state.queryParams.utilNum = '';

		let ids = res.data.list.map((item: any) => item.id);
		state.queryParams.communityIds = ids;
		emit('doSearch', state.queryParams);
	});
}

// 选择小区
function communityChange(community: any) {
	console.log({ community });
	state.communityName = community ? community.name : '';
	state.queryParams.communityId = community ? community.id : '';
	state.queryParams.buildNum = '';
	state.queryParams.utilNum = '';
	state.buildSelect = [];
	state.unitSelect = [];
	search();

	if (community.id) {
		getBuildNum(community.id);
	}
}

// 选择栋数
function buildChange(value: any) {
	state.queryParams.utilNum = '';
	state.unitSelect = [];
	getUnit();
	search();
}

// 选择单元
function unitChange(value: any) {
	search();
}

// 获取楼栋
function getBuildNum(communityId: any) {
	deviceApi.getBuildNum({ communityId }).then((res) => {
		state.buildSelect = res.data.list || [];
	});
}

// 获取单元
function getUnit() {
	let searchData = {
		communityId: state.queryParams.communityId,
		buildNum: state.queryParams.buildNum,
	};
	deviceApi.getUnitNum(searchData).then((res: any) => {
		state.unitSelect = res.data.list || [];
	});
}

//搜索
function search() {
	emit('doSearch', state.queryParams);
}

// 组织选择
function onOrgSelect(orgData: any) {
	state.queryParams.deptIds = orgData.ids;
	state.queryParams.dept = orgData.dept;

	getCommunityByDeptId(orgData.ids);
}

function orgTopSelect() {
	state.queryParams.deptIds = [];
	state.communityOptions = [];
	state.queryParams.communityId = '';
	state.communityName = '';
	state.queryParams.buildNum = '';
	state.queryParams.utilNum = '';
	state.queryParams.communityIds = [];
	emit('doSearch', state.queryParams);
}
</script>

<style scoped lang="scss">
:deep(.el-input) {
	width: auto;
}
</style>
